using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;

namespace ServerNET.Server
{
    public class CGapPay
    {
        public static int ProcessResult(string responseData, ref double GoldAdd)
        {
            GoldAdd = 0;
            int Result = 1;
            /*
            string responseData = @"<?xml version=""1.0"" encoding=""utf-8""?><MCardResult xmlns:xsi=""http:
            //www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchem
            a"">  <StatusCode>-99</StatusCode>  <TransactionID>10208</TransactionID>  <Amount
            >0</Amount>  <Message>Loi he thong nap the</Message></MCardResult>
                ";
            */
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.LoadXml(responseData);

                //Doc noi dung StatusCode
                XmlNode node = doc.SelectSingleNode("MCardResult//StatusCode");
                if (node == null)
                    throw new Exception("Can not find the StatusCode element.");
                int status = 0;
                if (!int.TryParse(node.InnerText, out status))
                    throw new Exception("Can not parsing the StatusCode value: " + node.Value);

                //Doc noi dung TransactionID
                node = doc.SelectSingleNode("MCardResult//TransactionID");
                if (node == null)
                    throw new Exception("Can not find the TransactionID element.");
                long transactionID = 0;
                if (!long.TryParse(node.InnerText, out transactionID))
                    throw new Exception("Can not parsing the TransactionID value: " + node.Value);

                //Doc noi dung cua Amount -So luong tien nap.
                node = doc.SelectSingleNode("MCardResult//Amount");
                if (node == null)
                    throw new Exception("Can not find the Amount element.");
                if (!double.TryParse(node.InnerText, out GoldAdd))
                    throw new Exception("Can not parsing the Amount value: " + node.Value);

                //Doc noi dung cua Message
                node = doc.SelectSingleNode("MCardResult//Message");
                if (node == null)
                    throw new Exception("Can not find the Message element.");
                string message = node.InnerText;


                //Thong bao ket qua
                if (status == 1)
                {
                    GoldAdd *= 10;
                    Result = 0;
                    Console.WriteLine("Nap the thanh cong. So tien nap la:" + GoldAdd.ToString() + ". So giao dich la:" + transactionID.ToString());                    
                }
                else
                {
                    Console.WriteLine("Loi khi nap the. Ly do:" + message + ". Ma loi: " + status.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error when processing the payment result:" + Environment.NewLine + ex.Message + Environment.NewLine + responseData);
            }

            return Result;
        }

        public static string DoGetRequest(string CardType, string CardNumber, string UserName, int CPID)
        {
            string url = "http://210.245.81.134:8888/payment/mcard.gap";
            string mpin = "BTVD4M";
            if (CPID == 1)
            {
                mpin = "RBKNIW";
            }
            string targetmobile = "84982121982";
            string targetemail = "abc@yahoo.com";
            string data = String.Format("mpin={0}&cardtype={1}&cardnumber={2}&targetname={3}&targetmobile={4}&targetemail={5}",
                        mpin, CardType, CardNumber, UserName, targetmobile, targetemail);

            Uri uri = new Uri(url + "?" + data);
            Console.WriteLine(uri);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
            req.Method = "GET";
            req.UserAgent = "Your agent information";
            req.Timeout = 100000;
            CredentialCache mycache = new CredentialCache();
            if (CPID == 1)
            {
                mycache.Add(new Uri(url), "Basic", new NetworkCredential("vtcg", "vtcg)(*"));
            }
            else
            {
                mycache.Add(new Uri(url), "Basic", new NetworkCredential("igap", "igap2012)(*"));
            }
            req.Credentials = mycache;

            //Get response data
            string responseBody = "";   //Noi dung tra ve
            string responseType = "";   //Loai noi dung tra ve (xml, html, ...)
            string responseServer = ""; //Ten may chu tra ve ket qua
            int responseStatus = 0;     //Trang thai HTTP
            string responseDescription = ""; //Mo ta trang thai HTTP

            try
            {
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();

                responseType = res.ContentType;
                responseServer = res.Server;
                responseStatus = (int)res.StatusCode;
                responseDescription = res.StatusDescription;

                //Neu ma tra ve la OK=200
                if (responseStatus == (int)HttpStatusCode.OK)
                {
                    //Doc noi dung tra ve tren Stream
                    Stream resst = res.GetResponseStream();
                    StreamReader sr = new StreamReader(resst, Encoding.UTF8);
                    responseBody = sr.ReadToEnd();
                }

                string StatusLine = String.Format("HTTP/{0} {1} {2}", res.ProtocolVersion, responseStatus, responseDescription);

                //Dong ket noi
                res.Close();
                Console.WriteLine("Response Status:" + StatusLine);
                Console.WriteLine("Content Type:" + res.ContentType);
                Console.WriteLine("Content Data:" + responseBody);
            }
            catch (Exception ex)
            {
                WebException webEx = (WebException)ex;

                Console.WriteLine("Get request response failed:" + Environment.NewLine + ex.Message);
            }

            return responseBody;
        }
    }
}
